<template>
	<div>
		<ProTable ref="proTable" title="定向邀请" :columns="columns" :request-api="getTableList" :init-param="initParam">
			<!-- 表格 功能 按钮 -->
			<template #searchHeader>
				<el-button type="primary" @click="onAddInvite" class="mb16" v-auth="'activity:invite:create:invoke'"> 新增邀请 </el-button>
			</template>

			<template #otherButton>
				<importUpload
					:limit="1"
					:importApi="fetchImportInvite"
					:params="{ activityId: Number(route.params.id) }"
					:onload="() => proTable?.getTableList()"
				>
					<el-button class="ml12 mr12" v-auth="'activity:invite:import:invoke'"> 导入邀请 </el-button>
				</importUpload>
				<el-button type="primary" link @click="downloadTemp"> 邀请模版下载 </el-button>
			</template>

			<template #tableHeader>
				<div class="mt20">
					<el-button type="primary" :disabled="!selectId.length" v-auth="'activity:invite:exec:invoke'" @click="onMessage()"> 短信邀请 </el-button>
					<el-button type="danger" :disabled="!selectId.length" v-auth="'activity:invite:delete:invoke'" @click="onDelete()"> 删除 </el-button>
				</div>
			</template>

			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>

			<!-- 表格操作 -->
			<template #operation="{ row }">
				<el-button type="primary" link @click="onMessage(row)"> 短信邀请 </el-button>
				<el-divider direction="vertical" />
				<el-button type="primary" link @click="onDelete(row.id)"> 删除 </el-button>
			</template>
		</ProTable>
		<Add :visible="addVisible" @handleClose="closeAdd"></Add>
		<Message :visible="msgVisible" :row="msgRow" @handleClose="closeMsg"></Message>
	</div>
</template>

<script setup lang="tsx" name="activityData">
import { onMounted, ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus';
import { NextLoading } from '/@/utils/loading';
import ProTable from '../../../../components/ProTable/index.vue';
import { ProTableInstance, ColumnProps } from '../../../../components/ProTable/interface';
import { fetchInviteList, fetchDelInvite, fetchImportInvite, fetchDownInviteTemp } from '/@/api/activity';
import { useRoute, useRouter } from 'vue-router';
import { encryptPhoneNumber } from '/@/utils/commonFunction';
import Add from './dialog/add.vue';
import Message from './dialog/message.vue';
import { useDownload } from '/@/hooks/useDownload';
import importUpload from '/@/components/upload/import.vue';

const route = useRoute();
const router = useRouter();

const addVisible = ref(false);

const msgVisible = ref(false);
const msgRow = ref();

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({
	searchType: 'NAME',
});

const selectId = computed(() => {
	return proTable.value?.selectedListIds || [];
});

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getTableList"
const getTableList = (params: any) => {
	let data = {
		...params,
		activityId: route.params.id,
	};

	return fetchInviteList(data);
};

// Excel 导入模板下载
const downloadTemp = () => {
	useDownload(fetchDownInviteTemp, `活动定向邀请模板`, {});
};

const searchArr = [
	{
		label: '姓名',
		value: 'NAME',
	},
	{
		label: '手机号',
		value: 'PHONE',
	},
];

// 表格配置项
const columns: ColumnProps<any>[] = [
	{
		prop: 'keywords',
		label: '用户搜索',
		isShow: false,
		search: {
			span: 2,
			render: (scope: any) => {
				const slot = {
					prepend: () => (
						<el-select
							v-model={scope.searchParam.searchType}
							placeholder="Select"
							style="width: 100px"
							onChange={(value) => {
								scope.searchParam.searchType = value;
							}}
						>
							{searchArr.map((item) => (
								<el-option key={item.value} label={item.label} value={item.value} />
							))}
						</el-select>
					),
				};
				return <el-input v-model={scope.modelValue} v-slots={slot} placeholder={getPlaceholder.value} maxlength={50}></el-input>;
			},
		},
	},
	{ type: 'selection', align: 'middle', width: 50 },
	{
		prop: 'name',
		label: '姓名',
	},
	{
		prop: 'phone',
		label: '手机号',
		minWidth: 100,
		render: (scope: any) => {
			return encryptPhoneNumber(scope.row.phone) || '-';
		},
	},
	{
		prop: 'roleDesc',
		label: '角色描述',
		minWidth: 120,
	},
	{
		prop: 'smsStatus',
		label: '短信邀请',
		minWidth: 120,
		search: { el: 'select', props: { placeholder: '选择短信邀请状态', clearable: true, filterable: true } },
		enum: [
			{
				label: '已发送',
				value: true,
			},
			{
				label: '未发送',
				value: false,
			},
		],
		render: (scope) => {
			return scope.row.smsStatus;
		},
	},
	{ prop: 'operation', label: '操作', fixed: 'right', width: 200, align: 'left' },
];

const getPlaceholder = computed(() => {
	const target = searchArr.find((item) => {
		return item.value == proTable.value?.searchParam.searchType;
	});
	return target ? `输入${target?.label}搜索` : '';
});

const onAddInvite = (row: any) => {
	addVisible.value = true;
};

const closeAdd = (success: boolean) => {
	addVisible.value = false;
	if (success) {
		proTable.value?.getTableList();
	}
};

const onMessage = (row?: any) => {
	if (row) {
		row['idList'] = [row.id];
	} else {
		row = proTable.value?.tableData[0];
		row['idList'] = selectId.value;
	}
	msgRow.value = row;
	msgVisible.value = true;
};

const closeMsg = (success: boolean) => {
	msgVisible.value = false;
	if (success) {
		proTable.value?.getTableList();
	}
};

const onDelete = (id?: any) => {
	ElMessageBox.confirm('确认删除该邀请？', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		const res = await fetchDelInvite({ idList: id ? [id] : selectId.value });
		if (res.code == 200) {
			ElMessage.success('删除成功');
			proTable.value?.getTableList();
		}
	});
};

// 页面加载时
onMounted(() => {
	NextLoading.done();
});
</script>

<style lang="scss">
.demo-tabs {
	.el-tabs__header {
		margin-bottom: 0;
	}
}
</style>
